<template>
  <div style="width: 100%; height: 100%">
    <div
      class="grid-container"
      v-if="listComputed.length && !infoLoadingRendonly"
    >
      <div class="grid-item" v-for="(item, index) in listComputed" :key="index">
        <div class="conttent-box">
          <img class="img" :src="item.screenshot" />
          <div class="info">
            <div class="title-box">
              <label class="title">
                {{ item.title }}
              </label>
            </div>
            <span class="title title_en">{{ item.titleEn }}</span>
            <span class="create-time">
              <span>
                <label class="log">{{
                  `${item.logData.num}${item.logData.num ? '次' : ''}`
                }}</label>
                {{ moment(item.createTime).format('YYYY-MM-DD HH:mm:ss') }}
              </span>
              <div>
                <el-icon class="icon link" @click="handleEdit(item)"
                  ><Edit
                /></el-icon>
                <el-icon class="icon link" @click="handleOpenNewPage(item)"
                  ><Link
                /></el-icon>
                <el-popconfirm
                  class="popconfirm-name"
                  width="160"
                  title="是否删除该书签！"
                  confirm-button-text="是"
                  cancel-button-text="否"
                  :teleported="false"
                  @confirm="confirmDelItem(item.id)"
                >
                  <template #reference>
                    <el-icon class="icon del"><Delete /></el-icon>
                  </template>
                </el-popconfirm>
              </div>
            </span>
          </div>
        </div>
      </div>
    </div>
    <div
      class="no-data"
      v-else-if="!listComputed.length && !infoLoadingRendonly"
    >
      <el-empty description="暂无数据！" />
    </div>
    <indexSkeleton v-else-if="infoLoadingRendonly" />
  </div>
</template>
<script setup name="List">
import {
  computed,
  inject,
  onMounted,
  onBeforeUnmount,
  watch,
  nextTick,
  ref,
} from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Edit,Link, Delete } from '@element-plus/icons-vue';
import { debounce, cloneDeep } from 'lodash';
import moment from 'moment';
import useSymbols from '../../compostions/useSymbols';
import { TYPE_NAME_SHU_QIAN } from '../../util/constant';
import indexSkeleton from './indexSkeleton.vue';

const router = useRouter();

const {
  listRendonly,
  getList,
  delListItem,
  setVisitItem,
  infoLoadingRendonly,
  setShowDialog,
} = inject(useSymbols);

onMounted(() => {
  getList();
  layout();

  const handleResize = debounce(() => {
    layout();
  }, 300);
  window.addEventListener('resize', handleResize);

  // 组件卸载前移除事件监听，避免内存泄露
  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
  });
});

// 瀑布流布局，dom高度计算
const layout = () => {
  const Doms = document.querySelectorAll('.grid-item');
  Array.from(Doms).forEach(function (dom, index) {
    const img = dom.querySelector('.img');
    const src = img.getAttribute('src');
    const image = new Image();
    image.src = src;
    const width = img.clientWidth;
    image.onload = () => {
      const w = image.width;
      const h = image.height;
      const ratio = h / w; // 高、宽比例
      const newHeight = Math.ceil(width * ratio) + 68;
      dom.style.gridRowEnd = `span ${~~(newHeight / 1) + 10}`;
    };
  });
};

// 编辑
const handleEdit = ({ id }) => {
  router.push({ path: '/index/book' ,query:{id}})
  setTimeout(() => {
    setShowDialog(true)
  }, 100);
}

// 调用electron主程序方法
const handleOpenNewPage = ({ id, url }) => {
  setVisitItem(id, TYPE_NAME_SHU_QIAN); // 统计方法
  getList();
  if (window.myApi) {
    window.myApi.sendOpenSellUrl(url);
  } else {
    window.open(url);
  }
};

// 删除
const confirmDelItem = async (id) => {
  await delListItem(id);
  ElMessage({
    message: '操作成功！',
    type: 'success',
    plain: true,
  });
};

// 计算随机颜色
const randomColor = () => {
  return Math.random().toString(16).slice(2, 8);
};

// 计算新的list，并添加颜色
const listComputed = computed(() => {
  const newList = cloneDeep(listRendonly.value);
  const imgBaseUrl = import.meta.env.VITE_BASE_FILE_SRC;
  return newList.map((item) => {
    item.color = `#${randomColor()}`;
    item.screenshot = imgBaseUrl + item.screenshot;
    return item;
  });
});

// 监听数据变化后，触发重新布局
watch(listComputed, async () => {
  await nextTick();
  layout();
});
</script>
<style scoped lang="less">
.grid-container {
  @cardRadius: 15px;

  position: relative;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(270px, 1fr));
  grid-column-gap: 12px;
  align-items: start;
  grid-auto-rows: 1px;
  box-sizing: border-box;
  height: calc(100% - 60px);
  .grid-item {
    grid-row-start: auto;
    .conttent-box {
      border-radius: @cardRadius;
      background-color: #fff;
      padding-bottom: 4px;
      transition: all 0.5s;
      &:hover {
        box-shadow: 0 0 10px #bebebe;
        transition: all 0.5s;
      }
      .img {
        width: 100%;
        height: 100%;
        box-shadow: 0 2px 8px #eee;
        border-top-left-radius: @cardRadius;
        border-top-right-radius: @cardRadius;
      }
      .info {
        padding: 0 8px;
        .title-box {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-top: 6px;

          .title {
            display: block;
            align-items: center;
            line-height: 20px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            color: #565656;
            font-size: 14px;
            font-weight: bold;
          }
        }
        .title_en {
          color: #888;
          line-height: 18px;
          font-size: 12px;
        }

        .create-time {
          display: flex;
          align-items: center;
          justify-content: space-between;
          line-height: 24px;
          margin-top: 4px;
          color: #9e9e9e;
          font-size: 12px;
          margin-bottom: 2px;
          .log {
            color: var(--system-primary-color);
            margin-inline-end: 4px;
          }
          .icons {
            display: flex;
            align-items: center;
            line-height: inherit;
            img {
              cursor: pointer;
              padding-left: 6px;
            }
          }
        }
      }
    }
  }
  .icon {
    font-size: 15px;
    padding: 0 3px;
    cursor: pointer;
    &:hover {
      transform: scale(1.05);
      filter: brightness(0.98);
    }
  }
  .link {
    color: #3f9eff;
  }
  .del {
    color: #f56c6c;
  }
  /deep/ .el-popover {
    border-radius: 15px;

    .el-button--primary {
      background-color: var(--system-primary-color);
      border: none;
    }

    .el-button {
      border-radius: 999px;
      border: none;
    }
  }
}
.no-data {
  padding-top: calc(35vh - 150px);
}
</style>
